# coding: utf-8
import web
import hashlib
from mysql import *
from helper import *
from sqlalchemy.sql import *
from sqlalchemy import exc
from time import time

class Auth:

    def __init__(self):
        pass

    def login(self, username, password):
        """
            User login.
            Params: String username, password email
            Return:
                Success: User object
                Fail: False
        """
        user = Session.query(User).filter(and_(User.username == username, User.password == self.hash_password(password))).all()
        if (len(user) != 1):
            print 'what the fuck'
            return False
        
        print user[0]
        web.ctx.session.user = user[0]
        return True
    
    def create_user(self, email, password, username):
        """
            Create a new user
            @params: string username, string password, string email
            @return: boolean
        """
        if Session.query(User).filter(or_(User.username == username, User.email == email)).count() != 0:
            return False
        
        password = self.hash_password(password)
        
        try:
            role = Session.query(Role).filter(Role.role=='user').one()
            user = User(username, password, email, True)
            user.roles.append(role)
            Session.commit()
        except exc.SQLAlchemyError:
            Session.rollback()
            return False
        
        return self.login(username, password)
    
    def password(self, id, password):
        """
            Update password
        """
        try:
            user = Session.query(User).filter(User.id==int(id)).one()
            user.password = self.hash_password(password)
            Session.commit()
            return True
        except exc.SQLAlchemyError:
            Session.rollback()
            return False
    
    def hash_password(self, password):
        """
            hash password
            @params: String password
            @return: String(64)
        """
        return hashlib.sha256(password).hexdigest()

    def username_available(self, username):
        """
            Check username exists...
            @params: String username
            @return: boolean
                @False: username can be use...
                @True: username exists...
        """
        return Session.query(User).filter(User.username==username).count()
    
    def email_available(self, email):
        """
            Check email exists...
            @params: String email
            @return: boolean
        """
        return Session.query(User).filter(User.email==email).count()
    
    
if __name__ == '__main__':
    Auth().create_user('zukhz', '123', 'zukhzz@gmail.com', '127.0.0.1')